package pure.csw.activemq.rediliverAndDeathletter;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.RedeliveryPolicy;
import pure.csw.common.Constant;

import javax.jms.*;
import java.io.IOException;

public class Consumer {
    public static void main(String[] args) throws JMSException, InterruptedException, IOException {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(Constant.URL);
        //设置重发的最大次数， 3次
        RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
        redeliveryPolicy.setMaximumRedeliveries(3);
        factory.setRedeliveryPolicy(redeliveryPolicy);
        Connection connection = factory.createConnection();
        connection.start();
        //开启一次会话，非事务，自动确认
        Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        //消息以队列的方式存储
        Queue queue = session.createQueue(Constant.QUEUENAME);
        //创建消息的消费者
        MessageConsumer consumer = session.createConsumer(queue);
        System.out.println("消息接收开始");
        //消费以监听的方式获取消息
        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                TextMessage textMessage = (TextMessage) message;
                try {
                    System.out.println("consumer:"+textMessage.getText());
                    //session.commit();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });
        //等待消息的监听完成
        Thread.sleep(5000);
        System.out.println("消息接受完毕");
        //关闭资源
        consumer.close();
        session.close();
        connection.close();
    }
}
